﻿@*
//------------------------------------------------------------------------------
//  此代码版权声明为全文件覆盖，如有原作者特别声明，会在下方手动补充
//  此代码版权（除特别声明外的代码）归作者本人Diego所有
//  源代码使用协议遵循本仓库的开源协议及附加协议
//  Gitee源代码仓库：https://gitee.com/diego2098/ThingsGateway
//  Github源代码仓库：https://github.com/kimdiego2098/ThingsGateway
//  使用文档：https://diego2098.gitee.io/thingsgateway-docs/
//  QQ群：605534569
//------------------------------------------------------------------------------
*@

@page "/login"
@layout BaseLayout
@inherits BaseComponentBase
@namespace ThingsGateway.Admin.Blazor
@using BlazorComponent;
@using Furion.DataEncryption;
@using Masa.Blazor.Presets;
@using ThingsGateway.Admin.Application;

<Ajax></Ajax>
@if (IsMobile)
{
    <MCard @onkeydown=Enter Height=@("100%")>
        @GetLoginCore()
    </MCard>
}
else
{
    <MRow NoGutters Style="height:100%">
        <MCol Md=5 Sm=12>
            <MSheet Elevation=1 Style="width:100%; height:100%;" Class="d-flex align-start flex-column mb-6">
                <div class="d-flex align-center ml-12 mt-12">
                    <MAvatar Size="40" Color="teal">
                        <span class="white--text text-h6">@CONFIG_TITLE?.GetNameLen2()</span>
                    </MAvatar>
                    <h1>@CONFIG_TITLE</h1>
                </div>
                <div class="d-flex align-center ml-12 mt-12 mb-auto">
                    <h3>@CONFIG_REMARK</h3>
                </div>
                <div class="d-flex align-center pa-2" style="width:100%;height:100%;">
                    <MImage Src=@(BlazorResourceConst.ResourceUrl+"images/login-left.svg")></MImage>
                </div>
            </MSheet>

        </MCol>

        <MCol Md=7 Sm=12 Align="AlignTypes.Center">
            <MRow Md=6 Sm=12 Justify="JustifyTypes.Center" Align="AlignTypes.Center">
                <MCard Class="px-16 py-12" @onkeydown=Enter>
                    @GetLoginCore()
                </MCard>
            </MRow>
        </MCol>

    </MRow>

}

@code {

    RenderFragment GetLoginCore()
    {
        RenderFragment ViewSubMenu =
    @<div class="mt-2 px-2 py-1 mx-auto text-center my-auto">
        <MAvatar Size=80>
            <MImage Src=@UserLogoUrl>
            </MImage>
        </MAvatar>
        <h5 class="mt-2 mb-12">@Welcome 👋</h5>
        <MTextField TValue="string"
                    Label=账号
                            Outlined
                    HideDetails="@("auto")"
        @bind-Value=@loginModel.Account>
        </MTextField>
        <MTextField TValue="string"
                    Class="mt-10"
                    Label="密码"
                    Type="@(_showPassword ? "text" : "password")"
                    AppendIcon="@(_showPassword ? "mdi-eye" : "mdi-eye-off")"
                    OnAppendClick="()=>_showPassword = !_showPassword"
                            Outlined
                    HideDetails="@("auto")"
        @bind-Value=@Password>
        </MTextField>
        @if (_showCaptcha)
        {
            <PImageCaptcha @ref=captcha @bind-Value="CaptchaValue"
                           TextFieldClass="mt-10 mx-auto"
                           Height="60"
                           Label=验证码 Outlined
                               OnRefresh="RefreshCode"
                               ErrorMessage=验证码错误>
                </PImageCaptcha>
        }
        <MButton Class="mt-11 rounded-4" OnClick=LoginAsync Height=46 Width=@("100%") Color="primary">登录</MButton>
    </div>
        ;
        return ViewSubMenu;
    }
}
@code {
    private string CaptchaValue;
    bool _showPassword;
    bool _showCaptcha;
    private readonly LoginInput loginModel = new();


    [Inject]
    AjaxService AjaxService { get; set; }


    string UserLogoUrl { get; set; } = BlazorResourceConst.ResourceUrl + "images/defaultUser.svg";

    string Welcome { get; set; }

    private ValidCodeOutput CaptchaInfo { get; set; }

    private string Password { get; set; }

    private string CONFIG_REMARK { get; set; }

    private string CONFIG_TITLE { get; set; }

    private async Task Enter(KeyboardEventArgs e)
    {
        if (e.Code == "Enter" || e.Code == "NumpadEnter")
        {
            await LoginAsync();
        }
    }
    private PImageCaptcha captcha;

    private async Task LoginAsync()
    {
        loginModel.ValidCodeReqNo = CaptchaInfo.ValidCodeReqNo;
        loginModel.ValidCode = CaptchaValue;
        loginModel.Password = DESCEncryption.Encrypt(Password, DESCKeyConst.DESCKey);
        if (IsMobile)
        {
            loginModel.Device = AuthDeviceTypeEnum.APP;
        }
        else
        {
            loginModel.Device = AuthDeviceTypeEnum.PC;
        }

        var ajaxOption = new AjaxOption { Url = "/auth/b/login", Data = loginModel, };
        var str = await AjaxService.GetMessageAsync(ajaxOption);
        if (str != null)
        {
            var ret = str.FromJsonString<UnifyResult<LoginOutput>>();
            if (ret.Code != 200)
            {
                if (captcha != null)
                {
                    await captcha.RefreshCode();
                }
                await PopupService.EnqueueSnackbarAsync(new("登录错误" + ": " + ret.Msg.ToString(), AlertTypes.Error));
            }
            else
            {
                await PopupService.EnqueueSnackbarAsync(new("登录成功", AlertTypes.Success));
                await Task.Delay(500);
                var userId = await App.GetService<SysUserService>().GetIdByAccountAsync(loginModel.Account);
                var data = await App.GetService<UserCenterService>().GetLoginDefaultRazorAsync(userId);
                var sameLevelMenus = await App.GetService<ResourceService>().GetaMenuAndSpaListAsync();
                if (NavigationManager.ToAbsoluteUri(NavigationManager.Uri).AbsolutePath == "/Login" || NavigationManager.ToAbsoluteUri(NavigationManager.Uri).AbsolutePath == "/")
                    await AjaxService.GotoAsync(sameLevelMenus.FirstOrDefault(a => a.Id == data)?.Component ?? "index");
                else
                    await AjaxService.GotoAsync(NavigationManager.Uri);
            }
        }
        else
        {
            if (captcha != null)
            {
                await captcha.RefreshCode();
            }
            await PopupService.EnqueueSnackbarAsync(new("登录错误", AlertTypes.Error));
        }
    }
    [Inject]
    private NavigationManager NavigationManager { get; set; }

    /// <inheritdoc/>
    protected override async Task OnParametersSetAsync()
    {
#if DEBUG
        loginModel.Account = "superAdmin";
        Password = "111111";
#endif
        GetCaptchaInfo();
        CONFIG_TITLE = (await App.GetService<IConfigService>().GetByConfigKeyAsync(ConfigConst.SYS_CONFIGBASEDEFAULT, ConfigConst.CONFIG_TITLE))?.ConfigValue;
        CONFIG_REMARK = (await App.GetService<IConfigService>().GetByConfigKeyAsync(ConfigConst.SYS_CONFIGBASEDEFAULT, ConfigConst.CONFIG_REMARK))?.ConfigValue;
        _showCaptcha = (await App.GetService<IConfigService>().GetByConfigKeyAsync(ConfigConst.SYS_CONFIGBASEDEFAULT, ConfigConst.CONFIG_CAPTCHA_OPEN))?.ConfigValue?.ToBoolean() == true;
        Welcome = "欢迎使用" + CONFIG_TITLE + "!";
        await base.OnParametersSetAsync();
    }

    private void GetCaptchaInfo()
    {
        CaptchaInfo = App.GetService<AuthService>().GetCaptchaInfo();
    }

    private Task<string> RefreshCode()
    {
        CaptchaInfo = App.GetService<AuthService>().GetCaptchaInfo();
        return Task.FromResult(CaptchaInfo.CodeValue);
    }
}